//
//  RCPSound.m
//  智能控制系统
//
//  Created by Rankin on 15/12/8.
//
//

#import "RCPSound.h"

@implementation RCPSound

- (void)pluginInitialize{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil];
    self.connectDev =[[ConnectDev alloc]init];
    _RCPSoundItemsDic = [[NSMutableDictionary alloc]init];
    _soundSourceArr = [[NSArray alloc]initWithObjects:MusicLoc_LOCAL,MusicLoc_SD,MusicLoc_USB
                               ,MusicLoc_AUX,MusicLoc_DLNA,MusicLoc_BT,MusicLoc_Fav, nil];
    [self.connectDev searchDevices];
}

- (void)init:(CDVInvokedUrlCommand*)command{
    self.callbackId = command.callbackId;
    
    // 写个定时器，定时获取 getAllDevices ， 当搜索到设备时，这个函数返回能搜索到的设备列表
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.8f target:self selector:@selector(updateList) userInfo:nil repeats:YES];
}

- (void)reset:(CDVInvokedUrlCommand*)command{
    _RCPSoundItemsDic = [[NSMutableDictionary alloc]init];
}

- (void)getAllDevice:(CDVInvokedUrlCommand*)command{
    
    NSArray *devies = [self.connectDev getAllDevices];
    
    
    CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:[self getArrFromRoomItemArr:devies]];
    [self.commandDelegate sendPluginResult:res callbackId:command.callbackId];
    
}

- (void)switchSoundSource:(CDVInvokedUrlCommand*)command{
    //[mac, soundSource]
    
}

- (void)playResume:(CDVInvokedUrlCommand*)command{
    NSString* mac = [command.arguments objectAtIndex:0];
    
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }
    
    [theItem playMusic: YES];
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}
- (void)playPause:(CDVInvokedUrlCommand*)command{
    NSString* mac = [command.arguments objectAtIndex:0];
    
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }
    [theItem playMusic: NO];
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}
- (void)setPlayMode:(CDVInvokedUrlCommand*)command{
    if ([command.arguments count]<2) {
        NSLog(@"error arguments");
        return;
    }
    NSString* mac = [command.arguments objectAtIndex:0];
    int mode = [[command.arguments objectAtIndex:1]intValue];
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }
    [theItem setPlayMode:[self changeAndroidPlayModeToIos:mode] ];
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}

- (void)playPrev:(CDVInvokedUrlCommand*)command{
    NSString* mac = [command.arguments objectAtIndex:0];
    
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }
    [theItem playPre];
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}
- (void)playNext:(CDVInvokedUrlCommand*)command{
    NSString* mac = [command.arguments objectAtIndex:0];
    
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }

    [theItem playNext];
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}
- (void)setVolume:(CDVInvokedUrlCommand*)command{
    if ([command.arguments count]<2) {
        NSLog(@"error arguments");
        return;
    }
    
    NSString* mac = [command.arguments objectAtIndex:0];
    int volume = [[command.arguments objectAtIndex:1]intValue];
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }
    
    [theItem changeVol:volume];
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}
- (void)setPlayProgress:(CDVInvokedUrlCommand*)command{
    if ([command.arguments count]<2) {
        NSLog(@"error arguments");
        return;
    }
    
    NSString* mac = [command.arguments objectAtIndex:0];
    int progress = [[command.arguments objectAtIndex:1]intValue];
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }
    
    [theItem changeMusicValue:theItem.m_playMusic.m_duration * progress / 100];
    
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}
- (void)rename:(CDVInvokedUrlCommand*)command{
    if ([command.arguments count]<2) {
        NSLog(@"error arguments");
        return;
    }
    
    NSString* mac = [command.arguments objectAtIndex:0];
    NSString* newName = [command.arguments objectAtIndex:1];
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }
    
    [theItem setDevName:newName];
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}
- (void)playMusicById:(CDVInvokedUrlCommand*)command{
    if ([command.arguments count]<2) {
        NSLog(@"error arguments");
        return;
    }
    
    NSString* mac = [command.arguments objectAtIndex:0];
    int musicId = [[command.arguments objectAtIndex:1]intValue];
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }
    
    [theItem playMusicWithID:musicId];
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}
- (void)addCurToFavorite:(CDVInvokedUrlCommand*)command{
    NSString* mac = [command.arguments objectAtIndex:0];
    
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }
    
    [theItem musicFav];
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}
- (void)allPlay:(CDVInvokedUrlCommand*)command{
}
- (void)allPause:(CDVInvokedUrlCommand*)command{}

- (void)setEqMode:(CDVInvokedUrlCommand*)command{
    if ([command.arguments count]<2) {
        NSLog(@"error arguments");
        return;
    }
    
    NSString* mac = [command.arguments objectAtIndex:0];
    int eqMode = [[command.arguments objectAtIndex:1]intValue];
    RoomItem* theItem = [[_RCPSoundItemsDic objectForKey:mac]objectForKey:@"device"];
    if (theItem==nil) {
        NSLog(@"there is not player");
        return;
    }
    eqMode =[self changeAndroidEqModeToIos:eqMode];
    [theItem setEQ:eqMode];
    [self sendMessageToJs:0 message:@"" callbackId:command.callbackId];
}

- (void)startListen:(CDVInvokedUrlCommand*)command{
    if (_timer==nil) {
        _timer =[NSTimer scheduledTimerWithTimeInterval:0.8f target:self selector:@selector(updateList) userInfo:nil repeats:YES];
    }
}
- (void)stopListen:(CDVInvokedUrlCommand*)command{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

/** 更新列表数据 */
- (void) updateList
{
    NSArray *aryDevList = [self.connectDev getAllDevices]; // 设备列表，设备对象 RoomItem
    if(aryDevList != nil
       || aryDevList.count != 0){
        
        RoomItem *item = nil;
        for(int i=0; i<aryDevList.count; i+=1)
        {
            
            item = (RoomItem*)[aryDevList objectAtIndex:i];
            if(item.m_playMusic ==nil) continue;
            
            
            NSMutableDictionary *thisItem = nil;
            if ((thisItem = [_RCPSoundItemsDic objectForKey:item.m_strMac])==nil) {
                NSMutableDictionary* curItemDic = [[NSMutableDictionary alloc]init];
                
                [curItemDic setObject:[item.m_dicMusicList mutableCopy] forKey:@"playList"];
                [curItemDic setObject:@"" forKey:@RCP_COVER];
                [curItemDic setObject:NOTNULL(item.m_strName) forKey:@"name"];
                [curItemDic setObject:NOTNULL(item.m_playMusic.m_strName) forKey:@"musicName"];
                [curItemDic setObject:item forKey:@"device"];
                
                
                [_RCPSoundItemsDic setObject:curItemDic forKey:item.m_strMac];
            }
            
            NSMutableDictionary *return_dic = [[NSMutableDictionary alloc]init];
            
            [return_dic setObject:@"stateChange" forKey:@RCP_CALLBACK_TYPE]; //为了配合js层，不同的值改变会用到不同的状态返回参数
            if (thisItem ==nil) { //todo 新发现设备
                [return_dic setObject:@"device" forKey:@RCP_CALLBACK_TYPE];
                
                NSLog(@"device");
            }
            else if (![NOTNULL(item.m_strName) isEqualToString: [thisItem objectForKey:@"name"]]) {//设备名称改变
                [return_dic setObject:@"nameChange" forKey:@RCP_CALLBACK_TYPE];
                [return_dic setObject:NOTNULL(item.m_strName) forKey:@"newName"];
                [thisItem setObject:NOTNULL(item.m_strName) forKey:@"name"];
                NSLog(@"nameChange");
            }
            
            else if (![NOTNULL(item.m_playMusic.m_strName) isEqualToString: [thisItem objectForKey:@"musicName"]]) {//播放新歌
                [return_dic setObject:@"playNew" forKey:@RCP_CALLBACK_TYPE];
                [thisItem setObject:NOTNULL(item.m_playMusic.m_strName) forKey:@"musicName"];
                [thisItem setObject:@"" forKey:@RCP_COVER];//playnew 的时候清空播放的cover
                NSLog(@"playNew changed");
            }
            
            else if (thisItem!=nil && [self checkPlayListsChange:[thisItem objectForKey:@"playList"] new:item.m_dicMusicList]) {//播放列表更新
                [return_dic setObject:@"soundSource" forKey:@RCP_CALLBACK_TYPE];
                [return_dic addEntriesFromDictionary:item.m_dicMusicList];
                
                [thisItem setObject:[item.m_dicMusicList mutableCopy] forKey:@"playList"];
                NSLog(@"soundSource");
            }

            else{
                // ---- 获取音乐封面 ----
                /** item.m_dicIcon 里面用图片的路径m_strPath为key保存已经缓存在内存中的封面图片，SDK会自动下载当前播放音乐的封面，所以只需要等待下载结束后，会自动保存在item.m_dicIcon中 ，当没有图片时，会返回一个NSNumber对象*/
                UIImage *imgIcon = NULL;
                id object = [item.m_dicIcon objectForKey:item.m_playMusic.m_strPath];
                if(object != NULL){
                    if([object isKindOfClass:[NSNumber class]] == YES){ // 返回的数据显示该音乐没有封面图片，则调用默认图片
                        //                    imgIcon = GetImg(DefaultImgName_Small);
                        
                    }
                    else if([object isKindOfClass:[UIImage class]] == YES){ // 替换为音乐封面
                        imgIcon = (UIImage*)object;
                        NSData* imgDatas = UIImagePNGRepresentation(imgIcon);
                        
                        NSString* base64EncoderString = [[NSString alloc]initWithFormat:@"data:image/png;base64,%@",[imgDatas base64Encoding] ];
                        
                        if (imgDatas!=nil && ![base64EncoderString isEqualToString:[thisItem objectForKey:@RCP_COVER]]) {
                            [return_dic setObject:@"cover" forKey:@RCP_CALLBACK_TYPE];  //回调封面
                            [return_dic setObject:base64EncoderString forKey:@RCP_COVER];
                            [thisItem setObject:base64EncoderString forKey:@RCP_COVER];
                            NSLog(@"fileCover");
                        }
                    }
                }
                
            }
            
            
            
            
            //                [return_dic setValue:@"" forKey:@RCP_ALUM_ID  ];
            //                [return_dic setValue:@"" forKey:@RCP_DLNA_UDN  ];
            //                [return_dic setValue:@"" forKey:@RCP_HOST_IP  ];
            //                [return_dic setValue:@"" forKey:@RCP_HOST_PORT  ];
            //                [return_dic setValue:@"" forKey:@RCP_IS_LINK_CTRL ];
            //                [return_dic setValue:@"" forKey:@RCP_IS_LINK_DLNA  ];
            //                [return_dic setValue:@"" forKey:@RCP_VOLUME_TMP  ];
            //                [return_dic setValue:@"" forKey:@RCP_NET_STATE  ];
            //                [return_dic setValue:@"" forKey:@RCP_PLAYER  ];
            //                [return_dic setValue:@"" forKey:@RCP_TICK_COUNT_TMP ];

            [return_dic setValuesForKeysWithDictionary:[self getDicFromRoomItem:item]];
            
            

           
            
            [self sendDictToJs:return_dic];
            return_dic = nil;
            

        }
    }
}

-(BOOL)checkPlayListsChange:(NSDictionary*)old new:(NSDictionary*)new{
    return ![old isEqualToDictionary:new];
}

-(id)formatData:(id)data{
    return data ==nil? @"" : data;
}

-(void) sendDictToJs:(NSDictionary *)message{
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message];
    [result setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:result callbackId:_callbackId];
}

- (void)onAppTerminate{
    [_timer invalidate];
    _timer = nil;
}

- (void)onResume{
    [self.connectDev searchDevices];
    NSLog(@"rcp onResume");
}

- (void)onPause{
    NSLog(@"rcp onPause");
    
}

-(NSNumber*)changeSoundSourceToAndroidType:(NSString*)soundSource{
//    LOCAL    : 0,
//    SD       : 1,
//    USB      : 2,
//    AUX1     : 3,
//    DLNA     : 4,
//    BT       : 5,
//    FAVORITE : 6
//#define MusicLoc_AUX        @"AUX"
//#define MusicLoc_BT         @"BT"
//#define MusicLoc_FM         @"FM"
//#define MusicLoc_LOCAL      @"LOCAL"
//#define MusicLoc_USB        @"USB"
//#define MusicLoc_SD         @"SD"
//#define MusicLoc_QQ         @"QQ"
//#define MusicLoc_DLNA       @"DLNA"
//#define MusicLoc_Fav        @"我的收藏"
    for(int i=0;i<_soundSourceArr.count;i++){
        if([soundSource isEqualToString:[_soundSourceArr objectAtIndex:i]]){
            return [[NSNumber alloc]initWithInt:i];
        }
    }
    return @-1;
}

-(NSString*)changeAndroidSoundSourceToIos:(int)soundSource{
    return _soundSourceArr[soundSource];
}

-(NSNumber*)changePlayModeToAndroidType:(int)playMode{
//    SEQUENCE   : 0,
//    RANDOM     : 1,
//    REPEAT_ONE : 2,
//    LOOP       : 3
//#define Mode_Single     1  // 播放控制－单曲循环
//#define Mode_Circle     2  // 播放控制－列表循环
//#define Mode_Order      3  // 播放控制－顺序播放
//#define Mode_Random     4  // 播放控制－随机播放
    int playModeArr[4] = {Mode_Order,Mode_Random ,Mode_Single,Mode_Circle};
    
    for(int i=0;i<4;i++){
        if(playMode == playModeArr[i]){
            return [[NSNumber alloc]initWithInt:i];
        }
    }
    return @-1;
}

-(int)changeAndroidPlayModeToIos:(int)playMode{
    int playModeArr[4] = {Mode_Order,Mode_Random ,Mode_Single,Mode_Circle};
    return playModeArr[playMode];
}

-(NSNumber*)changeEqModeToAndroidType:(int)eqMode{
//    NORMAL  : 0,
//    CLASSIC : 1,
//    JAZZ    : 2,
//    ROCK    : 3,
//    POP     : 4
//#define EQ_Normal       5  // EQ模式－普通模式
//#define EQ_GuDian       6  // EQ模式－古典模式
//#define EQ_JueShi       7  // EQ模式－爵士模式
//#define EQ_YaoGu        8  // EQ模式－摇滚模式
//#define EQ_LiuXing      9  // EQ模式－流行模式

    return [[NSNumber alloc]initWithInt:eqMode-5];
}

-(int)changeAndroidEqModeToIos:(int)eqMode{
    return eqMode+5;
}


-(NSDictionary*)getDicFromRoomItem:(RoomItem*)item{
    NSMutableDictionary* return_dic = [[NSMutableDictionary alloc]init];
    
    [return_dic setObject: [self changeEqModeToAndroidType:[item getEQ]] forKey:@RCP_EQ_MODEL];//声音类型（爵士神马的)
    
    [return_dic setObject:[self changeSoundSourceToAndroidType:NOTNULL(item.m_strListLocation)] forKey:@RCP_FLAG_LOCAL]; //当前播放的音源
    [return_dic setObject:[self changePlayModeToAndroidType:[item getPlayMode]] forKey:@RCP_PLAY_MODE ];//当前播放模式
    
    [return_dic setObject:NOTNULL([[NSNumber alloc] initWithInt:item.m_playMusic.m_ex_mute]) forKey:@RCP_MUTE ];
    
    
    [return_dic setObject:NOTNULL([[NSNumber alloc]initWithFloat:item.m_playMusic.m_ex_volumeCur]) forKey:@RCP_VOLUME_CUR  ];
    [return_dic setObject:NOTNULL([[NSNumber alloc]initWithFloat:item.m_playMusic.m_ex_volumeMax])  forKey:@RCP_VOLUME_MAX  ];
    [return_dic setObject:NOTNULL([[NSNumber alloc]initWithInt: item.m_playMusic.m_playing]) forKey:@RCP_PLAY_STATUS  ];
    [return_dic setObject:NOTNULL([[NSNumber alloc]initWithInt:item.m_playMusic.m_duration]) forKey:@RCP_DURATION  ];
    [return_dic setObject:NOTNULL([[NSNumber alloc]initWithInt: item.m_playMusic.m_musicid]) forKey:@RCP_MUSIC_ID  ];
    [return_dic setObject:NOTNULL(item.m_playMusic.m_strName) forKey:@RCP_MUSIC_NAME ];
    [return_dic setObject:NOTNULL(item.m_playMusic.m_strPath) forKey:@RCP_MUSIC_PATH ];
    [return_dic setObject:NOTNULL([[NSNumber alloc]initWithFloat:item.m_playMusic.m_time]) forKey:@RCP_MUSIC_TIME ];
    [return_dic setObject:NOTNULL(item.m_strType) forKey:@RCP_TYPE];
    [return_dic setObject:NOTNULL(item.m_strName) forKey:@RCP_NAME];
    [return_dic setObject:NOTNULL(item.m_strMac) forKey:@RCP_MAC];
    [return_dic setObject:NOTNULL(item.m_dicMusicList) forKey:@"soundSource"];
    
    [return_dic setObject:NOTNULL(item.m_playMusic.m_strArtist) forKey:@RCP_ARTIST];
    return return_dic;
}

-(NSArray*)getArrFromRoomItemArr:(NSArray*)items{
    NSMutableArray* retArr = [[NSMutableArray alloc]init];
    for(int i=0;i<items.count;i++){
        [retArr addObject:[self getDicFromRoomItem:items[i]]];
    }
    return retArr;
}


-(void)sendMessageToJs:(int)type message:(NSString*)message callbackId:(NSString*)callbackId{
    CDVPluginResult* cdvResult = nil;
    switch (type) {
        case 0:
            cdvResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
            break;
        case 1:
            cdvResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];
            break;
        default:
            cdvResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];
            break;
    }
    [self.commandDelegate sendPluginResult:cdvResult callbackId:callbackId];
}


@end
